package com.android.clinic.doctors.app.glide;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import com.android.clinic.doctors.app.ClinicDoctorsApplication;
import com.android.clinic.doctors.app.R;
import com.android.clinic.doctors.app.glide.transformation.GlideCircleTransform;
import com.android.clinic.doctors.app.glide.transformation.GlideRoundTransform;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.ViewTarget;
import com.bumptech.glide.request.transition.Transition;
import com.davemorrissey.labs.subscaleview.ImageSource;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;

import java.io.File;

/**
 * Created by cheng on 2018/6/19.
 */
public class ImageLoaderUtils {

    private static ImageLoaderUtils mInstance;
    private static RequestOptions option;
    private static RequestOptions optionHead;

    private ImageLoaderUtils() {
        option = new RequestOptions()
                .placeholder(R.drawable.icon_head_default)
                .dontAnimate()
                .skipMemoryCache(false)
                .diskCacheStrategy(DiskCacheStrategy.DATA)
                .error(R.drawable.icon_head_default);
        optionHead = option.clone();
        optionHead.placeholder(R.drawable.icon_un_login_head).error(R.drawable.icon_un_login_head);
        optionHead.transform(new GlideCircleTransform());
    }

    public static ImageLoaderUtils getInstance() {
        if (mInstance == null) {
            synchronized (ImageLoaderUtils.class) {
                if (mInstance == null) {
                    mInstance = new ImageLoaderUtils();
                    return mInstance;
                }
            }
        }
        return mInstance;
    }

    public void loadNormalHomeImage(Object url, final ImageView imageView) {
        GlideApp.with(imageView.getContext()).asBitmap().load(url).apply(option).into(getTarget(imageView));

    }

    public void loadHeadHomeImage(Object url, final ImageView imageView) {
        GlideApp.with(imageView.getContext()).asBitmap().load(url).apply(optionHead).into(getTarget(imageView));
    }


    public void loadNormalImage(Object url, ImageView imageView) {
        GlideApp.with(imageView.getContext()).load(url).apply(option).into(imageView);
    }


    public void loadHeadImage(Object url, ImageView imageView) {
        GlideApp.with(imageView.getContext()).load(url).apply(optionHead).into(imageView);
    }

    public void loadNormalImage(Object url, ImageView imageView, int width, int height) {
        ViewGroup.LayoutParams lp = imageView.getLayoutParams();
        lp.width = width;
        lp.height = height;
        imageView.setLayoutParams(lp);
        GlideApp.with(imageView.getContext()).load(url).override(width, height).apply(option).into(imageView);
    }

    public void loadHeadImage(Object url, ImageView imageView, int width, int height) {
        ViewGroup.LayoutParams lp = imageView.getLayoutParams();
        lp.width = width;
        lp.height = height;
        imageView.setLayoutParams(lp);
        GlideApp.with(imageView.getContext()).load(url).override(width, height).apply(optionHead).into(imageView);
    }

    public void loadRoundImage(Object url, ImageView imageView) {
        RequestOptions optionRoound = option.clone();
        optionRoound.transform(new GlideRoundTransform(20));
        GlideApp.with(imageView.getContext()).load(url).apply(optionRoound).into(imageView);
    }

    /**
     * 等比图片 用于广告定义尺寸
     */
    public void loadNormalImage(Object url, ImageView imageView, int ow, int width, int height) {
        int itemHeight = (int) (ow * height * 1.0f / width);
        ViewGroup.LayoutParams params;
        if (imageView.getLayoutParams() instanceof LinearLayout.LayoutParams) {
            params = new LinearLayout.LayoutParams(ow, itemHeight);
        } else if (imageView.getLayoutParams() instanceof RelativeLayout.LayoutParams) {
            params = new RelativeLayout.LayoutParams(ow, itemHeight);
        } else {
            params = new ViewGroup.LayoutParams(ow, itemHeight);
        }
        imageView.setLayoutParams(params);
        GlideApp.with(imageView.getContext()).load(url).override(width, height).apply(option).into(imageView);
    }

    /**
     * 加载图片并保存
     */
    public void loadImageAndSave(String url, final ImageView imageView) {
        GlideApp.with(imageView.getContext()).asBitmap().load(url).into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                FileUtils.write2album(imageView.getContext(), resource); //保存系统相册
                FileUtils.writeBitmap2File(resource, System.currentTimeMillis() + ".jpg"); //保存sd卡
                imageView.setImageBitmap(resource);
            }
        });
    }

    /**
     * 加载大图
     */
    public void loadBigImage(String url, SubsamplingScaleImageView imageView, final ProgressBar progressBar) {
        RequestBuilder request = GlideApp.with(imageView.getContext()).load(url);
        ViewTarget viewTarget = new ViewTarget<SubsamplingScaleImageView, BitmapDrawable>(imageView) {
            @Override
            public void onLoadStarted(@Nullable Drawable placeholder) {
                super.onLoadStarted(placeholder);
                progressBar.setVisibility(View.VISIBLE);
            }

            @Override
            public void onResourceReady(BitmapDrawable resource, Transition<? super BitmapDrawable> transition) {
                this.view.setImage(ImageSource.bitmap(resource.getBitmap()));
                progressBar.setVisibility(View.GONE);
            }
        };
        request.into(viewTarget);
    }

    public void clearImageMemoryCache(Context context) {
        try {
            if (Looper.myLooper() == Looper.getMainLooper()) { //只能在主线程执行
                GlideApp.get(context).clearMemory();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void clearImageDiskCache() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                GlideApp.get(ClinicDoctorsApplication.getInstance()).clearDiskCache();
            }
        }).start();
    }

    public String getCacheSize(Context context) {
        try {
            return FileUtils.getFormatSize(new File(context.getCacheDir() + "/"
                    + InternalCacheDiskCacheFactory.DEFAULT_DISK_CACHE_DIR));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public SimpleTarget<Bitmap> getTarget(final ImageView imageView) {
        return new SimpleTarget<Bitmap>() {
            @Override
            public void onLoadStarted(@Nullable Drawable placeholder) {
                super.onLoadStarted(placeholder);
                imageView.setImageDrawable(placeholder);
            }

            @Override
            public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                imageView.setImageBitmap(resource);
            }
        };
    }

}
